<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Db;

class Banner extends Base
{
	//广告列表
	public function index()
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);
			$list = Db::name('banner')->order('sort asc')->limit($start, $limit)->select();
			foreach ($list as $key => &$value) {
				$value['addtime'] = date('Y-m-d',$value['addtime']);
				$value['updatetime'] = date('Y-m-d',$value['updatetime']);
			}
			$count = Db::name('banner')->count();
			return $this->json_data($count, $list);
		}
		return $this->fetch();
	}

	public function add()
	{
		return $this->fetch();
	}

	//编辑栏目1-1
	public function edit($id)
	{
		if (empty($id)) {
			$info = [];
		} else {
			$info = Db::name('banner')->where('id', $id)->find();
		}
		$this->assign('info', $info);
		return $this->fetch('edit');
	}
	//编辑栏目1-2
	public function save()
	{
		$status = 0;
		$msg = "操作失败";
		$data = $this->request->param();

		if (empty($data['id'])) {
			$update = [
				'img' => $data['img'],
				'sort' => $data['sort'],
				'addtime' => time(),
				'updatetime' => time()
			];
			//执行操作
			$res = Db::table('banner')->insert($update);
			if ($res) {
				$status = 1;
				$msg = "添加成功";
				$cname = '添加广告';
				$ctype = '添加';
			}
		} else {
			$id = $data['id'];
			$update = [
				'img' => $data['img'],
				'sort' => $data['sort'],
				'updatetime' => time()
			];
			//执行更新操作
			$res = Db::table('banner')->where('id', $id)->update($update);

			if ($res) {
				$status = 1;
				$msg = "更新成功";
				$cname = '更新广告';
				$ctype = '更新';
			}
		}
		adminlog($cname, $ctype);
		return ['status' => $status, 'msg' => $msg];
	}

	//删除栏目1-1
	public function del($id)
	{
		$status = 0;
		$msg = "操作失败";
		if (empty($id)) {
			$msg .= '，ID不存在';
		} else {
			$del = Db::name('banner')->where('id', $id)->delete();
			if ($del) {
				$status = 1;
				$msg = "删除成功";
				adminlog('删除id:' . $id, '删除');
			}
		}
		return ['status' => $status, 'msg' => $msg];
	}

}
